/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */

// reference local blank image
Ext.BLANK_IMAGE_URL = CONTEXT_PATH + '/ext/resources/images/default/s.gif';
Ext.SSL_SECURE_URL = CONTEXT_PATH + '/blank.html';

// Encoding for ajax form POST
/** @namespace Ext.lib */
Ext.lib.Ajax.defaultPostHeader += '; charset=UTF-8';


// Timeout to 120 seconds
Ext.Ajax.timeout = 120000;

Ext.namespace("Org");

/**
 * Upload dialog.
 *
 * @param config the configuration.
 */
Org.UploadDialog = function(config) {
	Org.UploadDialog.superclass.constructor.call(this, config);
};

Ext.extend(Org.UploadDialog, Ext.Window, {

	form: null,

	initComponent: function() {

		Ext.apply(this, {
			renderTo: Ext.getBody(),
			modal: true,
			iconCls: 'icon-file-add',
			title: MSG['importedfiles.upload'],
			bodyStyle: 'padding:5px'
		});

		this.form = new Ext.FormPanel({
			fileUpload : true,
			width : 400,
			height: 120,
			frame : true,
			enctype: 'multipart/form-data',
			bodyStyle : 'padding: 10px 10px 0 10px;',
			labelWidth : 60,
			defaults : {
				msgTarget : 'side'
			},
			items : [{
				xtype : 'hidden',
				name : 'organization',
				value : Main.app.getUser().organization.id
			}, {
				xtype : 'field',
				inputType : 'file',
				fieldLabel : MSG['file.file'],
				name : 'file',
				anchor : '95%',
				buttonCfg : {
					text : '',
					iconCls : 'upload-icon'
				}
			}, {
				xtype : 'datefield',
				fieldLabel :  MSG['file.date'],
				name : 'date',
				format : 'd/m/Y',
				value : new Date()
			}],
			buttons : [{
				text : MSG['button.save'],
				scope: this,
				handler : function() {
					if (this.form.getForm().isValid()) {
						this.form.getForm().submit({
							url : CONTEXT_PATH + '/secure/orgadmin/import/file/upload.json',
							waitTitle: MSG['wait.title'],
							waitMsg : MSG['file.uploading'],
							success : function(/*fp, o*/) {
								notifySuccess(MSG['uploaded'], MSG['file.upload.ok']);
							},
							failure : function(/*fp, o*/) {
								notifyError(MSG['warning'], MSG['file.upload.ko']);
							},
							scope: this
						});
					}
				}
			}, {
				text : MSG['button.reset'],
				scope: this,
				handler : function() {
					this.form.getForm().reset();
				}
			}]
		});

		this.layout = 'fit';
		this.items = this.form;

		Org.UploadDialog.superclass.initComponent.call(this);
	},

	onUploadSuccess: function() {
		this.close();
		Main.app.addPanel(new Org.ImportedFilePanel());
	}
});

/**
 *	Survey edit panel.
 *
 * @param config the configuration.
 */
Org.ImportedFileEditorPanel = function(config) {
	Org.ImportedFileEditorPanel.superclass.constructor.call(this, config);
};

Ext.extend(Org.ImportedFileEditorPanel, Ext.Panel, {

	file: null,

	answerStore : null,

	answersGrid: null,

	answerRecord: null,

	answersPageToolbar: null,

	questionStore: null,

	questionsGrid: null,

	questionRecord: null,

	questionsPageToolbar: null,

	waitDlg: null,

	initComponent: function() {
		this.layout = 'border';

		this.title = MSG['file'] + ' - '+ this.file.filename;
		this.closable = true;
		this.autoShow = true;
		this.iconCls = 'icon-file-go';

		// Tools
		this.tools = [{
			id: 'close',
			handler: this.onClose,
			scope: this
		}];

		this.answerRecord = Ext.data.Record.create([
			{name: 'id', type: 'long'},
			{name: 'creationDate'},
			{name: 'status'},
			{name: 'surveyId'},
			{name: 'surveyCode'},
			{name: 'actionId'},
			{name: 'actionCode'},
			{name: 'entityId'},
			{name: 'councilId'},
			{name: 'internetConnection'},
			{name: 'originId'}
		]);

		this.answerStore = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/orgadmin/import/survey/find.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort : true,
			baseParams : {
				id : this.file.id,
				organization : Main.app.getUser().organization.id
			},
			reader: new Ext.data.JsonReader({id: 'id'}, this.answerRecord),
			fields: ['id', 'creationDate', 'status', 'surveyId', 'surveyCode', 'actionId',  'actionCode',  'entityId', 'councilId', 'internetConnection','originId']
		});

		this.answerStore.on("beforeload",
				function() {
					this.waitDlg = Ext.Msg.wait(MSG['wait.title'], MSG['wait.message']);
				}, this);

		this.answerStore.on("load",
				function() {
					if(this.waitDlg) {
						this.waitDlg.hide();
					}
				}, this);


		this.answersPageToolbar =  new Ext.PagingToolbar({
			store: this.answerStore,
			displayInfo: true,
			pageSize: 100,
			items:[
				'-', {
					text: MSG['button.remove'],
					iconCls: 'icon-remove',
					handler: this.onRemoveSelectedAnswer,
					scope: this
				}, {
					text: MSG['button.save'],
					iconCls: 'icon-disk',
					handler: this.onSaveSelectedAnswer,
					scope: this
				}
			]
		});

		this.answersGrid = new Ext.grid.EditorGridPanel({
			title: MSG['survey.headers'],
			autoScroll:true,
			clicksToEdit:1,
			region:'center',
			viewConfig: {
				emptyText: MSG['survey.answers.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([{
				header: MSG['survey.header'],
				dataIndex: 'id',
				width: 20,
				sortable: true,
				editable: false
			},{
				header: MSG['survey.header.status'],
				dataIndex: 'status',
				width: 30,
				sortable: true,
				editable: false,
				renderer : function(r) {
					return MSG[r.name];
				}
			},{
				header: MSG['survey.creation.date'],
				dataIndex: 'creationDate',
				width: 30,
				sortable: true,
				renderer: function(r,metadata) {
					if(Ext.isDate(r)) {
						metadata.attr = 'style="color:green"';
						return Ext.util.Format.date(r, "d/m/Y");
					} else {
						if (/^\d{2}\/\d{2}\/\d{2,4}$/.test(r)) {
							metadata.attr='style="color:green"';
						} else {
							if (r.length > 0) {
								metadata.attr='style="color:red"';
							} else {
								metadata.attr='style="background-color:red"';
							}
						}
					}
					return r;
				},
				editor: new Ext.form.DateField({ format: "d/m/Y", allowBlank: false })
			}, {
				header: MSG['survey.code'],
				dataIndex: 'surveyCode',
				width: 20,
				sortable: true,
				editor: new Ext.form.TextField({allowBlank: false, maxLength: 5, vtype: 'surveyCode'}),
				renderer : function (value, metadata, record) {
					if (record.data.surveyId == 0) {
						metadata.attr='style="color:red"';
					} else {
						metadata.attr='style="color:green"';
					}
					return value;
				}
			},{
				header: MSG['survey.action.id'],
				dataIndex: 'actionCode',
				width: 20,
				sortable: true,
				editor: new Ext.form.TextField({ allowBlank: false, maxLength: 20 }),
				renderer : function (value, metadata, record) {
					if (record.data.actionId == 0) {
						metadata.attr='style="color:red"';
					} else {
						metadata.attr='style="color:green"';
					}
					return value;
				}
			},{
				header: MSG['survey.entity.id'],
				dataIndex: 'entityId',
				width: 40,
				sortable: true,
				editor: new Ext.form.TextField({allowBlank: false, minLength: 9, maxLength: 9, vtype: 'DNI'}),
				renderer: function(value,metadata, record) {
					if (Common.validateNIF(value)) {
						metadata.attr='style="color:green"';
					} else {
						metadata.attr='style="color:red"';
					}
					return value;
				}
			},{
				header: MSG['survey.council.id'],
				dataIndex: 'councilId',
				width: 40,
				sortable: true,
				editor: new Ext.form.TextField({allowBlank: false, minLength: 6, maxLength: 6}),
				renderer: function(value,metadata) {
					if (isNaN(value)){
						metadata.attr='style="color:red"';
					} else {
						metadata.attr='style="color:green"';
					}
					return value;
				}
			},{
				header: MSG['survey.header.internet'],
				dataIndex: 'internetConnection',
				width: 40,
				sortable: true,
				editor: new Common.SimpleCombo({
					data: Common.InternetConnection,
					allowBlank: false
				}),
				renderer: function(v) {
					if(v == 1) {
						return  MSG['yes'];
					} else {
						return  MSG['no'];
					}
				}
			}]),
			store: this.answerStore,
			selModel: new Ext.grid.RowSelectionModel(),
			bbar: this.answersPageToolbar
		});

		this.questionRecord = Ext.data.Record.create([
			{name: 'header', type:'long'},
			{name: 'questionNumber', type:'int'},
			{name: 'question'},
			{name: 'status'},
			{name: 'questionCode'},
			{name: 'preference'}
		]);
		// Store
		this.questionStore =  new Ext.data.JsonStore({
			url: CONTEXT_PATH +'/secure/orgadmin/import/survey/unit/find.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort: false,
			reader: new Ext.data.ArrayReader({id: 'id'}, this.questionRecord),
			fields: ['header', 'questionNumber', 'question', 'status', 'questionCode', 'preference']
		});

		this.questionsPageToolbar = new Ext.PagingToolbar({
				store: this.questionStore,
				displayInfo: true,
				pageSize: 100,
				items:[
					'-', {
						text: MSG['button.remove'],
						iconCls: 'icon-remove',
						handler: this.onRemoveSelectedAnswerUnit,
						scope: this
					}, {
						text: MSG['button.save'],
						iconCls: 'icon-disk',
						handler: this.onSaveSelectedAnswerUnit,
						scope: this
					}
				]
			});

		this.questionsGrid = new Ext.grid.EditorGridPanel({
			title: MSG['survey.answers.units'],
			autoScroll:true,
			collapsible: true,
			width: 500,
			clicksToEdit:2,
			region:'east',
			split: true,
			viewConfig: {
				emptyText: MSG['survey.answers.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([{
				header: MSG['survey.header'],
				dataIndex: 'header',
				width: 20,
				sortable: true,
				editable: false
			},{
				header: MSG['survey.answer.questionNumber'],
				dataIndex: 'questionNumber',
				width: 20,
				sortable: true,
				editable: false
			},{
				header: MSG['survey.answer.status'],
				dataIndex: 'status',
				width: 30,
				sortable: true,
				editable: false,
				allowBlank: false,
				renderer : function(r) {
					return MSG[r.name];
				}
			},{
				header: MSG['survey.answer.questionCode'],
				dataIndex: 'questionCode',
				width: 60,
				sortable: true,
				allowBlank: false,
				editor: new Ext.form.TextField({ allowBlank: false, maxLength: 20, vtype: 'questionCode'}),
				validator : new function(value) {
					return Ext.num(value, 0) <= 0;
				},
				renderer: function(value,metadata,record) {
					if (record.questionCode != 0) {
						if (value.length >0 && Ext.num(value,0) !=0 ) {
							metadata.attr='style="color:green"';
						} else {
							metadata.attr='style="color:red"';
						}
					} else {
						metadata.attr='style="color:red"';
					}
					return value;
				}
			},{
				header: MSG['survey.answer.preference'],
				dataIndex: 'preference',
				width: 30,
				sortable: true,
				renderer: function(r) {
					switch(r) {
						case 1:
							return MSG['training.presential'];
						case 2:
							return MSG['training.remote'];
						case 3:
							return MSG['training.mixed'];
					}
					return r;
				},
				editor: new Common.SimpleCombo({
					data: Common.TrainingPreferences,
					allowBlank: false
				})
			}]),
			store: this.questionStore,
			selModel: new Ext.grid.RowSelectionModel(),
			bbar: this.questionsPageToolbar
		});

		this.items = [this.answersGrid,this.questionsGrid];

		this.answersGrid.on("rowdblclick", this.onSelectAnswer, this);
		this.answersPageToolbar.doLoad(0);
		Org.ImportedFileEditorPanel.superclass.initComponent.call(this);
	},

	onSelectAnswer: function(grid, rowIndex/*, evt*/) {
		var record = grid.getStore().getAt(rowIndex);
		this.questionStore.baseParams = { idHeader: record.data.id };
		this.questionsPageToolbar.doLoad(0);
	},

	onClose: function() {
		Main.app.addPanel(null);
	},

	onCancel: function() {
		Main.app.closePanel(this);
	},

	onRemoveSelectedAnswer: function(){
		var selections = this.answersGrid.getSelectionModel().getSelections();

		if (selections.length > 0){
			var elements = [];
			var i;
			for (i=0; i<selections.length; i++){
				elements.push(selections[i].get('id'));
			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/import/survey/delete.json',
				params: {
					id: elements
				},
				scope: this,
				success: function(){
					notifySuccess(MSG['delete'], MSG['delete.success']);
					this.answersPageToolbar.onClick('refresh');
					this.questionStore.removeAll();
				},
				failure: function(){
					notifyError(MSG['delete'], MSG['delete.error']);
					this.answersPageToolbar.onClick('refresh');
					this.questionStore.removeAll();
				}
			});


		}
	},

	onRemoveSelectedAnswerUnit: function(){

		var selections = this.questionsGrid.getSelectionModel().getSelections();

		if (selections.length > 0){
			var header = null;
			var elements = [];
			var i;
			for (i=0; i<selections.length; i++){
				if(header == null) {
					header = selections[i].get('header');
				}
				elements.push(selections[i].get('questionNumber'));
			}

			var record = this.questionsGrid.getSelectionModel().getSelected();
			this.questionStore.remove(record);
			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/import/survey/unit/delete.json',
				params: {
					header: header,
					questionNumber : elements
				},
				scope: this,
				success: function(){
					notifySuccess(MSG['delete'], MSG['delete.success']);
					this.questionsPageToolbar.onClick('refresh');
				},
				failure: function(){
					notifyError(MSG['delete'], MSG['delete.error']);
					this.questionsPageToolbar.onClick('refresh');
				}
			});
		}
	},

	onSaveSelectedAnswer: function(){

		var records = this.answerStore.getModifiedRecords();

		if(records != null && records.length > 0) {

			var id = [];
			var entityId = [];
			var surveyCode = [];
			var actionCode = [];
			var internetConnection = [];
			var creationDate = [];
			var councilId = [];

			var i = 0, t = null;
			for(i = 0; i < records.length; ++i) {
				id.push(records[i].get('id'));
				entityId.push(records[i].get('entityId'));
				surveyCode.push(records[i].get('surveyCode'));
				actionCode.push(records[i].get('actionCode'));
				internetConnection.push(records[i].get('internetConnection'));
				councilId.push(records[i].get('councilId'));
				t = records[i].get('creationDate');
				if(Ext.isDate(t)) {
					creationDate.push(Ext.util.Format.date(t, "d/m/Y"));
				} else {
					creationDate.push(t);
				}

			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/import/survey/save.json',
				params: {
					id: id,
					entityId: entityId,
					surveyCode: surveyCode,
					actionCode: actionCode,
					internetConnection: internetConnection,
					creationDate: creationDate,
					councilId : councilId
				},
				scope: this,
				success: function(){
					notifySuccess(MSG['save'], MSG['save.success']);
					this.answersPageToolbar.onClick('refresh');
				},
				failure: function(){
					notifyError(MSG['save'], MSG['save.error']);
					this.answersPageToolbar.onClick('refresh');
				}
			});

		}
	},

	onSaveSelectedAnswerUnit: function(){

		var records = this.questionStore.getModifiedRecords();

		if(records != null && records.length > 0) {

			var header = null;
			var questionNumber = [];
			var preference = [];
			var questionCode = [];
			

			var i = 0;
			for(i = 0; i < records.length; ++i) {
				if(header == null) {
					header = (records[i].get('header'));
				}
				questionNumber.push(records[i].get('questionNumber'));
				preference.push(records[i].get('preference'));
				questionCode.push(records[i].get('questionCode'));
				
			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/import/survey/unit/save.json',
				params: {
					header : header,
					questionNumber: questionNumber,
					preference : preference,
					questionCode : questionCode
				},
				scope: this,
				success: function(){
					notifySuccess(MSG['save'], MSG['save.success']);
					this.questionsPageToolbar.onClick('refresh');
				},
				failure: function(){
					notifyError(MSG['save'], MSG['save.error']);
					this.questionsPageToolbar.onClick('refresh');
				}
			});


		}
	}

});


/**
 * Imported file management dialog.
 *
 * @param config the configuration.
 */
Org.ImportedFilePanel = function(config) {
	Org.ImportedFilePanel.superclass.constructor.call(this, config);
};

Ext.extend(Org.ImportedFilePanel, Ext.Panel, {

	searchForm: null,

	waitDlg: null,

	resultsStore: null,

	pageToolbar: null,

	resultsGrid: null,

	initComponent: function() {
		this.layout = 'border';
		this.title = MSG['files'];
		this.closable = true;
		this.autoShow = true;
		this.iconCls = 'icon-file-find';

		// Tools
		this.tools = [{
			id: 'close',
			handler: this.onClose,
			scope: this
		}];

		// Search form
		this.searchForm = new Ext.FormPanel({
			region: 'west',
			split: true,
			collapsible: true,
			title: MSG['files'],
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'textfield',
				name: 'filename',
				fieldLabel: MSG['file.name'],
				maxLength: 200
			}, {
				xtype: 'simplecombo',
				hiddenName: 'status',
				fieldLabel: MSG['file.status'],
				data: Common.ImportedFileStatus,
				width: 100
			},{
				xtype: 'datefield',
				name: 'fromImportDate',
				fieldLabel: MSG['from'],
				maxLength: 60
			},{
				xtype: 'datefield',
				name: 'toImportDate',
				fieldLabel: MSG['to'],
				maxLength: 60
			},{
				xtype: 'hidden',
				name: 'organization',
				value: Main.app.getUser().organization.id
			}],
			buttons: [{
				text: MSG['button.search'],
				iconCls: 'icon-search',
				handler: this.onSearch,
				scope: this
			},{
				text: MSG['button.reset'],
				iconCls: 'icon-cancel',
				handler: this.onReset,
				scope: this
			}]
		});

		// Reader

		this.ImportFileRecord = Ext.data.Record.create([
			{name: 'id',type:'int'},
			{name: 'status'},
			{name: 'filename'},
			{name: 'importDate'},
			{name: 'firstDate'},
			{name: 'lastDate'},
			{name: 'totalRecords',type:'int'},
			{name: 'correctRecords',type:'int'},
			{name: 'warnedRecords',type:'int'}
		]);
		// Store
		this.resultsStore = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/orgadmin/import/file/find.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort: true,
			reader: new Ext.data.JsonReader({id: 'id'}, this.ImportFileRecord),
			fields: ['id', 'status', 'filename', 'importDate', 'firstDate', 'lastDate', 'totalRecords', 'correctRecords', 'warnedRecords']
		});

		this.resultsStore.on("beforeload",
				function() {
					this.waitDlg = Ext.Msg.wait(MSG['wait.title'], MSG['wait.text']);
					this.resultsStore.baseParams = this.searchForm.getForm().getRawValues();
				}, this);

		this.resultsStore.on("load",
				function() {
					if(this.waitDlg) {
						this.waitDlg.hide();
					}
				}, this);

		// Pagination toolbar
		this.pageToolbar = new Ext.PagingToolbar({
			store: this.resultsStore,
			displayInfo: true,
			pageSize: 100,
			plugins: [new Common.PageSizePlugin(MSG['page.size'])],
			items:[
				'-', {
					text: MSG['button.remove'],
					iconCls: 'icon-remove',
					handler: this.onRemoveSelected,
					scope: this
				}, {
					text: MSG['button.process'],
					iconCls: 'icon-process',
					handler: this.onProcessSelected,
					scope: this
				}, {
					text: MSG['button.validate'],
					iconCls: 'icon-ok',
					handler: this.onValidateSelected,
					scope: this
				}
			]
		});

		// Grid
		this.resultsGrid = new Ext.grid.GridPanel({
			title: MSG['result.title'],
			region: 'center',
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([
				{header: MSG['file.id'], dataIndex: 'id', width: 20, sortable: true},
				{header: MSG['file.status'], dataIndex: 'status', width: 20, sortable: true,	renderer : function(r) {
					return MSG[r.name];
				}},
				{header: MSG['file.name'], dataIndex: 'filename', width: 45, sortable: true},
				{header: MSG['file.importDate'], dataIndex: 'importDate', width: 20, sortable: true},
				{header: MSG['file.firstDate'], dataIndex: 'firstDate', width: 20, sortable: true},
				{header: MSG['file.lastDate'], dataIndex: 'lastDate', width: 20, sortable: true},
				{header: MSG['file.record.total'], dataIndex: 'totalRecords', width: 25, sortable: true},
				{header: MSG['file.record.correct'], dataIndex: 'correctRecords', width: 25, sortable: true},
				{header: MSG['file.record.warned'], dataIndex: 'warnedRecords', width: 20, sortable: true}
			]),
			store: this.resultsStore,
			bbar: this.pageToolbar
		});

		this.items = [this.searchForm, this.resultsGrid];

		this.pageToolbar.doLoad(0);

		this.resultsGrid.on("rowdblclick", this.onSelectedFile, this);

		Org.ImportedFilePanel.superclass.initComponent.call(this);
	},

	onClose: function() {
		Main.app.addPanel(null);
	},

	onSearch: function() {
		this.pageToolbar.doLoad(0);
	},

	onReset: function() {
		this.searchForm.getForm().reset();
		this.pageToolbar.doLoad(0);
	},


	onSelectedFile: function(grid, rowIndex/*, evt*/){
		var record = grid.getStore().getAt(rowIndex);

		var surveyEditorPanel = new Org.ImportedFileEditorPanel({ file: record.data});
		Main.app.addPanel(surveyEditorPanel);
	},

	onRemoveSelected: function(){

		var selections = this.resultsGrid.getSelectionModel().getSelections();
		if (selections.length > 0){
			var elements = [];
			var i;
			for (i=0; i<selections.length; i++){
				elements.push(selections[i].get('id'));
			}


			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/import/file/delete.json',
				params: {
					id: elements,
					organization: Main.app.getUser().organization.id
				},
				scope: this,
				success: function(){
					notifySuccess(MSG['delete'], MSG['delete.success']);
					this.pageToolbar.onClick("refresh");
				},
				failure: function(){
					notifyError(MSG['delete'], MSG['delete.error']);
					this.pageToolbar.onClick("refresh");
				}
			});
		}
	},

	onProcessSelected: function(){
		var selections = this.resultsGrid.getSelectionModel().getSelections();
		if (selections.length > 0){
			var elements = [];
			var i;
			for (i=0; i<selections.length; i++){
				elements.push(selections[i].get('id'));
			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/import/file/process.json',
				params: {
					id: elements,
					organization: Main.app.getUser().organization.id
				},
				scope: this,
				success: function(){
					notifySuccess(MSG['process'], MSG['process.success']);
					this.pageToolbar.onClick("refresh");
				},
				failure: function(){
					notifyError(MSG['process'], MSG['process.error']);
					this.pageToolbar.onClick("refresh");
				}
			});

		}
	},

	onValidateSelected: function(){
		var selections = this.resultsGrid.getSelectionModel().getSelections();
		if (selections.length > 0){
			var elements = [];
			var i;
			for (i=0; i<selections.length; i++){
				elements.push(selections[i].get('id'));
			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/import/file/validate.json',
				params: {
					id: elements,
					organization: Main.app.getUser().organization.id
				},
				scope: this,
				success: function(){
					notifySuccess(MSG['validate'], MSG['validate.success']);
					this.pageToolbar.onClick("refresh");
				},
				failure: function(){
					notifyError(MSG['validate'], MSG['validate.error']);
					this.pageToolbar.onClick("refresh");
				}
			});

		}
	}

});

/**
 * Module definition.
 */
MODULES['7_importedfiles'] = {

	menu: null,

	init: function() {
		// Initialize common menu
		this.menu = new Ext.menu.Menu({
			items: [{
				text: MSG['importedfiles.upload'],
				iconCls: 'icon-file-add',
				handler: this.onUploadFile,
				scope: this
			},{
				text: MSG['importedfiles.list'],
				iconCls: 'icon-file-find',
				handler: this.onListImportedFiles,
				scope: this
			}]
		});


		// Add menu to toolbar
		Main.app.mainToolbar.add({
			text: MSG['importedfiles.title'],
			iconCls: 'icon-file-go',
			menu: this.menu
		});
	},

	onUploadFile: function() {
		var dialog = new Org.UploadDialog();
		dialog.show();
	},

	onListImportedFiles: function() {
		var panel = new Org.ImportedFilePanel();
		Main.app.addPanel(panel);
	}
};